package com.lhf.aicloud.controller;

import cn.hutool.http.HttpRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lhf.aicloud.entity.Answer;
import com.lhf.aicloud.entity.enums.AIModelEnum;
import com.lhf.aicloud.entity.enums.AITypeEnum;
import com.lhf.aicloud.service.IAnswerService;
import com.lhf.aicloud.utils.*;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import okhttp3.HttpUrl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author: lhf
 * @date: Created in 2024/08/11
 * @description:
 */
@Slf4j
@RestController
@RequestMapping("/xunfei")
public class XunFeiController {

    @Value("${xunfei.chat.url}")
    private String chatUrl;

    @Value("${xunfei.chat.api-key}")
    private String apiKey;

    @Value("${xunfei.chat.api-secret}")
    private String apiSecret;

    @Value("${xunfei.draw.api-key}")
    private String drawApiKey;

    @Value("${xunfei.draw.api-secret}")
    private String drawApiSecret;

    @Value("${xunfei.draw.host-url}")
    private String drawHostUrl;

    @Value("${xunfei.draw.appId}")
    private String appId;

    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private IAnswerService answerService;

    @Resource
    private MinIoUtil minIoUtil;

    @Resource
    private RedisTemplate<Object, Object> redisTemplate;

    /**
     * 调用讯飞大模型的对话功能
     */
    @RequestMapping("/chat")
    public ResponseEntity chat(String question) throws JsonProcessingException {
        if (!StringUtils.hasLength(question.trim())) {
            return ResponseEntity.error(400, "问题不能为空");
        }
        log.info("prompt: {}", question);

        // 构建请求体
        String bodyJson = "{\n" +
                "    \"model\":\"generalv3.5\",\n" +
                "    \"messages\": [\n" +
                "        {\n" +
                "            \"role\": \"user\",\n" +
                "            \"content\": \"" + question + "\"\n" +
                "        }\n" +
                "    ]\n" +
                "}";

        String result = HttpRequest.post(chatUrl)
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer " + apiKey + ":" + apiSecret)
                .body(bodyJson)
                .execute()
                .body();
        log.info("result: {}", result);

        // 将结果转换为 map
        HashMap<String, Object> resultMap = objectMapper.readValue(result, HashMap.class);

        if (!resultMap.get("code").equals(0)) {
            return ResponseEntity.error(resultMap.get("message").toString());
        }

        ArrayList choices = (ArrayList) resultMap.get("choices");
        LinkedHashMap<String, Object> choicesMap = (LinkedHashMap<String, Object>) choices.get(0);
        LinkedHashMap<String, Object> message = (LinkedHashMap<String, Object>) choicesMap.get("message");
        String content = (String) message.get("content");

        // 将结果保存到 数据库
        Answer answer = new Answer();
        answer.setQuestion(question);
        answer.setAnswer(content);
        answer.setModel(AIModelEnum.XUNFEI.getValue());
        answer.setCreatetime(LocalDateTime.now());
        answer.setUid(SecurityUtils.getCurrentUser().getUid());
        answer.setType(AITypeEnum.CHAT.getValue());
        boolean addResult = answerService.save(answer);
        if (addResult) {
            return ResponseEntity.success(content);
        }
        return ResponseEntity.error("数据保存失败！");
    }

    /**
     * 调用讯飞大模型的绘画功能
     */
    @RequestMapping("/draw")
    public ResponseEntity draw(String question) throws Exception {
        if (!StringUtils.hasLength(question.trim())) {
            return ResponseEntity.error(400, "问题不能为空");
        }
        log.info("prompt: {}", question);

        String url = getAuthUrl(drawHostUrl, drawApiKey, drawApiSecret);

        String bodyJson = "{\n" +
                "  \"header\": {\n" +
                "    \"app_id\": \"" + appId + "\"\n" +
                "    },\n" +
                "  \"parameter\": {\n" +
                "    \"chat\": {\n" +
                "      \"domain\": \"general\",\n" +
                "      \"width\": 512,\n" +
                "      \"height\": 512\n" +
                "      }\n" +
                "    },\n" +
                "  \"payload\": {\n" +
                "    \"message\": {\n" +
                "      \"text\": [\n" +
                "        {\n" +
                "          \"role\": \"user\",\n" +
                "          \"content\": \"" + question + "\"\n" +
                "        }\n" +
                "      ]\n" +
                "    }\n" +
                "  }\n" +
                "}";

        String result = HttpRequest.post(url)
                .body(bodyJson)
                .execute()
                .body();
        // 解析结果
        HashMap resultMap = objectMapper.readValue(result, HashMap.class);
        LinkedHashMap<String, Object> payload = (LinkedHashMap<String, Object>) resultMap.get("payload");
        LinkedHashMap<String, Object> choices = (LinkedHashMap<String, Object>) payload.get("choices");
        ArrayList<LinkedHashMap<String, Object>> text = (ArrayList<LinkedHashMap<String, Object>>) choices.get("text");
        LinkedHashMap<String, Object> contentMap = text.getFirst();
        String content = contentMap.get("content").toString();
        // base64 转 图片，存储到 MinIo 中
        String imageUrl = "";
        String imageName = "xunfei-draw-" + UUID.randomUUID().toString().replace("-", "") + ".png";
        try (InputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(content))) {
            // 上传到 minio
            imageUrl = minIoUtil.upload("xunfei/" + imageName, inputStream, "image/png");

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        log.info("imageUrl: {}", imageUrl);

        // 将结果保存到 数据库
        Answer answer = new Answer();
        answer.setQuestion(question);
        answer.setAnswer(imageUrl);
        answer.setModel(AIModelEnum.XUNFEI.getValue());
        answer.setCreatetime(LocalDateTime.now());
        answer.setUid(SecurityUtils.getCurrentUser().getUid());
        answer.setType(AITypeEnum.DRAW.getValue());
        boolean addResult = answerService.save(answer);
        if (addResult) {
            return ResponseEntity.success(imageUrl);
        }
        return ResponseEntity.error("数据保存失败！");
    }

    /**
     * 获取讯飞大模型聊天历史信息
     */
    @RequestMapping("/chatHistory")
    public ResponseEntity chatHistory() {
        // 获取当前用户ID
        Long uid = Objects.requireNonNull(SecurityUtils.getCurrentUser()).getUid();
        String cacheKey = AppVariable.getListCacheKey(uid, AIModelEnum.XUNFEI.getValue(), AITypeEnum.CHAT.getValue());
        ArrayList cacheList = (ArrayList) redisTemplate.opsForValue().get(cacheKey);
        if (cacheList != null && !cacheList.isEmpty()) {
            return ResponseEntity.success(cacheList);
        }
        // 构建查询条件
        LambdaQueryWrapper<Answer> answerLambdaQueryWrapper = new LambdaQueryWrapper<Answer>()
                .eq(Answer::getUid, uid)
                .eq(Answer::getType, 1)
                .eq(Answer::getModel, AIModelEnum.XUNFEI.getValue())
                .orderByDesc(Answer::getCreatetime);
        // 查询
        List<Answer> list = answerService.list(answerLambdaQueryWrapper);
        redisTemplate.opsForValue().set(cacheKey, list, 1, TimeUnit.DAYS);
        return ResponseEntity.success(list);
    }

    /**
     * 获取讯飞大模型绘画历史信息
     */
    @RequestMapping("/drawHistory")
    public ResponseEntity drawHistory() {
        // 获取当前用户ID
        Long uid = Objects.requireNonNull(SecurityUtils.getCurrentUser()).getUid();
        String cacheKey = AppVariable.getListCacheKey(uid, AIModelEnum.XUNFEI.getValue(), AITypeEnum.DRAW.getValue());
        ArrayList cacheList = (ArrayList) redisTemplate.opsForValue().get(cacheKey);
        if (cacheList != null && !cacheList.isEmpty()) {
            return ResponseEntity.success(cacheList);
        }
        // 构建查询条件
        LambdaQueryWrapper<Answer> answerLambdaQueryWrapper = new LambdaQueryWrapper<Answer>()
                .eq(Answer::getUid, uid)
                .eq(Answer::getType, AITypeEnum.DRAW.getValue())
                .eq(Answer::getModel, AIModelEnum.XUNFEI.getValue())
                .orderByDesc(Answer::getCreatetime);
        // 查询
        List<Answer> list = answerService.list(answerLambdaQueryWrapper);
        redisTemplate.opsForValue().set(cacheKey, list, 1, TimeUnit.DAYS);
        return ResponseEntity.success(list);
    }

    /**
     * 讯飞大模型url签名方法
     *
     * @param hostUrl
     * @param apiKey
     * @param apiSecret
     * @return
     * @throws Exception
     */
    public static String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {
        URL url = new URL(hostUrl);
        // 时间
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        // date="Thu, 12 Oct 2023 03:05:28 GMT";
        // 拼接
        String preStr = "host: " + url.getHost() + "\n" + "date: " + date + "\n" + "POST " + url.getPath() + " HTTP/1.1";
        // System.err.println(preStr);
        // SHA256加密
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
        mac.init(spec);

        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        // Base64加密
        String sha = Base64.getEncoder().encodeToString(hexDigits);
        // System.err.println(sha);
        // 拼接
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);
        // 拼接地址
        HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder().
                addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8))).
                addQueryParameter("date", date).
                addQueryParameter("host", url.getHost()).
                build();

        // System.err.println(httpUrl.toString());
        return httpUrl.toString();
    }
}
